package com.wpzf.zxhc.controller;

import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.ndhc.utils.CheckUtil;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.service.WpzfDockService;
import com.wpzf.zxhc.utils.OBSDeleteUnits;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/putInfo")
public class WpzfDockController {

    @Autowired
    TokenService tokenService;

    @Autowired
    WpzfDockService wpzfDockGxServiceImpl;


    //推送年度地块信息
    @RequestMapping(value = "/putNdDkInfo", method = RequestMethod.POST)
    public AjaxResult putNdDkInfo(@RequestBody List<Map<String, Object>> param) {
        String rest = wpzfDockGxServiceImpl.putNdDkInfo(param);
        return AjaxResult.success("推送年度地块信息", rest);
    }

    // 上传OBS文件
    @RequestMapping(value = "/uploadOBSFile", method = RequestMethod.POST)
    public AjaxResult uploadFile(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "dkbh") String dkbh,
                                 @RequestParam(value = "xzqdm") String xzqdm,
                                 @RequestParam(value = "pch") String pch) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String user_xzqdm = loginUser.getSysUser().getXzqdm();
        if (user_xzqdm.equals(xzqdm.substring(0, 2))) {
            try {
                String rest = "";
                if (file == null) {
                    return AjaxResult.error("上传文件有误！");
                } else {
                    if (!file.isEmpty()) {
                        String saveName = file.getOriginalFilename();
                        // 创建保存路径
                        String savePath = System.getProperty("user.dir") + "\\" + "S/wpzf2024/FJData" + "\\" + pch + "\\" + xzqdm + "\\" + dkbh;
                        // 保存文件的文件夹
                        File folder = new File(savePath);
                        // 判断路径是否存在,不存在则自动创建
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }
                        //文件存到本地
                        file.transferTo(new File(folder, saveName));
                        //文件地址
                        String filePath = savePath + "\\" + saveName;

                        String OBSAddress = "S/wpzf2024/FJData/" + pch + "/" + xzqdm + "/" + dkbh + "/" + saveName;
                        AtomicInteger attemptCount = new AtomicInteger(0);
                        String log;
                        do {
                            log = OBSUploadUnits.OBSUpload(OBSAddress, filePath);
                            attemptCount.incrementAndGet();
                        } while (!log.equals("success") && attemptCount.get() < 5);

                        File f = new File(filePath);
                        if (f.exists()) {
                            if (f.isFile()) {
                                f.delete();
                                System.out.println("文件删除成功：" + filePath);
                            }
                        } else {
                            System.out.println("文件不存在：" + filePath);
                        }
                        Map<String, Object> map = new HashMap<>();
                        if ("success".equals(log)) {
                            rest = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;
                        } else {
                            return AjaxResult.error(saveName + "obs多次尝试上传仍未成功");
                        }
                    } else {
                        return AjaxResult.error("上传文件不能为空！");
                    }
                }
                return AjaxResult.success("文件上传成功", rest);
            } catch (Exception ex) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("上传文件异常，请联系管理员" + ex);
            }
        } else {
            return AjaxResult.error("当前用户无该省权限！");
        }
    }

    // 删除OBS文件
    @RequestMapping(value = "/deleteOBSFile", method = RequestMethod.POST)
    public AjaxResult deleteOBSFile(@RequestParam(value = "fileName") String fileName,
                                    @RequestParam(value = "dkbh") String dkbh,
                                    @RequestParam(value = "xzqdm") String xzqdm,
                                    @RequestParam(value = "pch") String pch) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String user_xzqdm = loginUser.getSysUser().getXzqdm();
        if (user_xzqdm.equals(xzqdm.substring(0, 2))) {
            try {
                String OBSAddress = "S/wpzf2024/FJData" + "/" + pch + "/" + xzqdm + "/" + dkbh + "/" + fileName;
                OBSDeleteUnits.OBSDelete(OBSAddress);
                return AjaxResult.success("文件删除成功");
            } catch (Exception ex) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("删除文件异常，请联系管理员" + ex);
            }
        } else {
            return AjaxResult.error("当前用户无该省权限！");
        }
    }

    //撤销、存储图斑信息 文件不需要存储到桶里
    @RequestMapping(value = "/saveResult", method = RequestMethod.POST)
    public AjaxResult saveResult(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
            String rest = wpzfDockGxServiceImpl.saveResult(param);
            if (!rest.isEmpty()) {
                if (rest.contains("存储失败")) {
                    return AjaxResult.error("撤销、存储图斑信息" + rest);
                } else {
                    return AjaxResult.success("撤销、存储图斑信息", rest);
                }
            }
            return AjaxResult.success("撤销、存储图斑信息", rest);
        } catch (Exception e) {
            return AjaxResult.error("撤销、存储图斑信息 失败");
        }
    }

    //以图斑为单位撤销数据
    @RequestMapping(value = "/deleteResult", method = RequestMethod.POST)
    public AjaxResult deleteResult(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
            String rest = wpzfDockGxServiceImpl.deleteResult(param);
            return AjaxResult.success("以图斑为单位撤销数据", rest);
        } catch (Exception e) {
            return AjaxResult.error("以图斑为单位撤销数据");
        }
    }

    //查询存储信息 分页
    @RequestMapping(value = "/queryResult", method = RequestMethod.POST)
    public AjaxResult queryResult(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
            List<Map<String, Object>> rest = wpzfDockGxServiceImpl.queryResult(param);
            Integer cnt = wpzfDockGxServiceImpl.queryResultCount(param);
            return AjaxResult.success("查询存储信息", rest, cnt);
        } catch (Exception e) {
            return AjaxResult.error("查询存储信息 失败", e);
        }
    }

    //查询db质检记录 分页
    @RequestMapping(value = "/queryQualityTestingResult", method = RequestMethod.POST)
    public AjaxResult queryQualityTestingResult(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());
            List<Map<String, Object>> rest = wpzfDockGxServiceImpl.queryQualityTestingResult(param);
            Integer cnt = wpzfDockGxServiceImpl.queryQualityTestingResultCount(param);
            return AjaxResult.success("查询存储信息", rest, cnt);
        } catch (Exception e) {
            return AjaxResult.error("查询存储信息 失败", e);
        }
    }

    //获取db
    @RequestMapping(value = "getDB", method = RequestMethod.POST)
    public AjaxResult getDB(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());

            String user_xzqdm = param.get("user_xzqdm") + "";
            String xzqdm = param.get("xzqdm") + "";

            if (user_xzqdm.equals(xzqdm.substring(0, 2))) {
                List<Map<String, Object>> rest = wpzfDockGxServiceImpl.getDB(param);
                return AjaxResult.success("获取db", rest);
            } else {
                return AjaxResult.error("当前用户无该行政区权限！");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取db失败", e.getMessage());
        }
    }

    //获取wp_sjsb_qualitytesting_nd_2024数据  8007
    @RequestMapping(value = "/queryQualitytesting", method = RequestMethod.POST)
    public AjaxResult queryQualitytesting(@RequestBody Map<String, Object> param) {
        try {
            List<Map<String, Object>> rest = wpzfDockGxServiceImpl.queryQualitytesting(param);
            return AjaxResult.success("获取数据", rest);
        } catch (Exception e) {
            return AjaxResult.error("获取数据 失败", e.getMessage());
        }
    }

    //获取wp_sjsb_qualitytesting_nd_2024数据  8007
    @RequestMapping(value = "/queryQualitytestingByXzqdm", method = RequestMethod.POST)
    public AjaxResult queryQualitytestingByXzqdm(@RequestBody Map<String, Object> param) {
        try {
            Map<String, Object> rest = wpzfDockGxServiceImpl.queryQualitytestingByXzqdm(param);
            return AjaxResult.success("根据行政区获取数据", rest);
        } catch (Exception e) {
            return AjaxResult.error("根据行政区获取数据 失败", e.getMessage());
        }
    }

    //更新wp_sjsb_qualitytesting_nd_2024状态  8007
    @RequestMapping(value = "/updateQualitytestingByStatus", method = RequestMethod.POST)
    public AjaxResult updateQualitytestingByStatus(@RequestBody Map<String, Object> param) {
        try {
            Integer rest = wpzfDockGxServiceImpl.updateQualitytestingByStatus(param);
            return AjaxResult.success("更新数据", rest);
        } catch (Exception e) {
            return AjaxResult.error("更新数据 失败", e.getMessage());
        }
    }


    @Log(title = "质检文件上传", businessType = BusinessType.OTHER)
    @Transactional
    @RequestMapping(value = "/uplogOBSFile", method = RequestMethod.POST)
    public AjaxResult uploadOBSFile(@RequestParam(value = "file") MultipartFile file,
                                    @RequestParam(value = "xzqdm") String xzqdm) {
        try {
            if (file == null) {
                return AjaxResult.error("请选择需要上传的文件");
            } else {
                if (!file.isEmpty()) {
                    String originName = file.getOriginalFilename();
                    // 创建保存路径
                    String savePath = System.getProperty("user.dir") + "\\" + "checkresult" + "\\" + xzqdm;
                    // 保存文件的文件夹
                    File folder = new File(savePath);
                    // 判断路径是否存在,不存在则自动创建
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    String saveName = originName;

                    //文件存到本地
                    file.transferTo(new File(folder, saveName));
                    //文件地址
                    String filePath = savePath + "\\" + saveName;
                    String OBSAddress = "XXSCWJ/" + saveName;

                    String log = OBSUploadUnits.OBSUpload(OBSAddress, filePath);
                    Map<String, Object> rest = new HashMap<>();
                    if ("success".equals(log)) {
                        String fj = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;
                        rest.put("filePath", fj);
                        return AjaxResult.success("文件上传成功", rest);
                    } else {
                        return AjaxResult.error("文件上传成功", rest);
                    }
                }
                return AjaxResult.error("文件上传失败");
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("上传文件异常，请联系管理员" + ex);
        }
    }


    @Value("${tempath}")
    public String tempath;

    @Log(title = "质检文件存储", businessType = BusinessType.OTHER)
    @Transactional
    @RequestMapping(value = "/saveChecekResult", method = RequestMethod.POST)
    public AjaxResult saveChecekResult(@RequestBody Map<String, Object> param) {
        try {
            Map<String, Object> map = new HashMap<>();

            String xzqdm = param.get("xzqdm") + "";
            String signurl = param.get("signurl") + "";
            String logurl = param.get("logurl") + "";
            String message = "";
            map.put("xzqdm", xzqdm);
            if (!logurl.isEmpty() && logurl != "") {
                map.put("logurl", logurl);
                map.put("signurl", signurl);
                //下载log信息
                String fileName = logurl.substring(logurl.lastIndexOf("/") + 1);
                String logPath = downloadByIO(logurl, tempath, fileName);
                File file = new File(logPath);
                CheckUtil checkUtil = new CheckUtil();
                Map<String, Object> checklog = checkUtil.chedklog(logPath, xzqdm);
                String excelurl = checklog.get("excelPath").toString();

                if (checklog.get("code").equals(200)) {
                    excelurl = checklog.get("excelPath").toString();
                    message = checklog.get("info").toString();
                } else {
                    message = checklog.get("info").toString();
                }
                map.put("excelurl", excelurl);
                map.put("message", message);
                String checktime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());
                map.put("checktime", checktime);

                Integer rest = wpzfDockGxServiceImpl.updateQualitytestingByInfo(map);
                return AjaxResult.success("质检结果上传成功", rest);
            } else {
                return AjaxResult.error("上传文件为空");
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("上传文件异常，请联系管理员" + ex);
        }
    }

    public static String downloadByIO(String url, String saveDir, String fileName) {
        BufferedOutputStream bos = null;
        InputStream is = null;
        try {
            byte[] buff = new byte[8192];
            is = new URL(url).openStream();
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count = 0;
            while ((count = is.read(buff)) != -1) {
                bos.write(buff, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return saveDir + "\\" + fileName;
    }

    //查询国土云数据包解析进度
    @RequestMapping(value = "/queryDataAnalysis", method = RequestMethod.POST)
    public Map<String, Object> queryDataAnalysis(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("user_xzqdm", loginUser.getSysUser().getXzqdm());

            String user_xzqdm = param.get("user_xzqdm") + "";
            String xzqdm = param.get("xzqdm") + "";

            if (user_xzqdm.equals(xzqdm.substring(0, 2))) {
                List<Map<String, Object>> rest = wpzfDockGxServiceImpl.queryDataAnalysisList(param);
                return AjaxResult.success("查询国土云数据包解析进度",rest);
            } else {
                return AjaxResult.error("当前用户无该行政区权限！");
            }
        } catch (Exception e) {
            return AjaxResult.error("查询数据包解析进度 失败", e.getMessage());
        }
    }

    //查询所有提交后的国土云返回结果
    @RequestMapping(value = "/queryDataAnalysisList", method = RequestMethod.POST)
    public List<Map<String, Object>> queryDataAnalysisList(@RequestBody Map<String, Object> param) {
        List<Map<String, Object>> rest = wpzfDockGxServiceImpl.queryDataAnalysisList(param);
        return rest;
    }

}
